var basePath = (function () {
    var url = window.location + "";
    var h = url.split("//");
    var x = h[1].split("/");
    return h[0] + "//" + window.location.host + "/" + x[1] + "/";
})();

var getValidRecoverVal = function (value) {
    return value == 0 ? "" : value;
};
/*
 *数据的自动注入
 * @param options:{
 *   data:标准json格式数据
 *   mode:结果集的指定属性名
 * }
 * @param callBack 回调函数 默认参数为当前执行的jQuery对象
 */
(function ($) {

    var els = {
        input: "INPUT",
        checkbox: "CHECKBOX",
        radio: "RADIO",
        text: "TEXT",
        select: "SELECT"
    };

    var mode = {
        ID: "ID"
    };

    var methods = {
        setVal: function ($obj, val, callBack) {
            if ($obj.is(els.input)) {
                switch ($obj.attr("TYPE").toUpperCase()) {
                    case els.text:
                        $obj.val(val);
                        break;
                    case els.checkbox:
                    case els.radio:
                        $obj.prop("checked", true);
                        break;
                }
                if ($.isFunction(callBack))
                    callBack($obj);
                return;
            }

            if ($obj.is(els.select)) {
                $obj.children("option").each(function () {
                    if ($(this).val() == val)
                        $(this).prop("selected", true)
                });
                if ($.isFunction(callBack))
                    callBack($obj);
            }
        },
        attrInject: function ($objs, options, callBack) {
            var the = this;
            var currentId;
            $.each(options.data, function (key, val) {
                $objs.each(function () {
                    currentId = $(this).attr(mode.ID);
                    if (currentId == undefined || $.trim(currentId) == ""){
                        return true;
                    }
                    if (key.toUpperCase() == currentId.toUpperCase()) {
                        the.setVal($(this), val, callBack);
                        return false;
                    }
                })
            });
        }
    };

    $.fn.autoInject = function (options, callBack) {
        var defaults = {
            data: {},
            mode: ""
        };

        options = $.extend(true, defaults, options);

        switch (options.mode.toUpperCase()) {
            case mode.ID:
                methods.attrInject(this, options, callBack);
                break;
        }

        return this; //返回jquery选取对象的集合jQuery以便链式操作
    }
}(jQuery));

var validate = function () {
    var $obj;
    var $objParent;
    var notNumber = function (val) {
        return !$.isNumeric(val);
    };
    return {
        init: function (jqueryObject) {
            $obj = jqueryObject;
            $objParent = $obj.closest(".form-group");
        },
        invalid: function () {
            $objParent.removeClass("has-success").addClass("has-error");
        },
        valid: function () {
            $objParent.removeClass("has-error").addClass("has-success");
        },
        addInvalid: function (jqObj) {
            this.init(jqObj);
            this.invalid();
        },
        addValid: function (jqObj) {
            this.init(jqObj);
            this.valid();
        },
        hasNotNumber: function (valArray) {
            var length = valArray.length;
            if (length == undefined)
                return false;
            for (var i = 0; i < length; i++) {
                if (notNumber(valArray[i]))
                    return true;
            }
            return false;
        },
        allNumber:function (valArray){
            return this.hasNotNumber(valArray)? false:true;
        },
        hasZero: function (valArray) {
            var l = valArray.length;
            if (l == undefined)
                return false;
            for (var i = 0; i < l; i++) {
                if (valArray[i] == 0)
                    return true;
            }
            return false;
        },
        isNotNumber: function (val) {
            return notNumber(val);
        },
        isNumber:function (val){
            return $.isNumeric(val);
        }
    }
}();

$(function () {
    //此函数为了处理firefox及chrome中，在弹出的窗口中点击ckeditor的上传图片，显示的input无法获取光标的问题
    $.fn.modal.Constructor.prototype.enforceFocus = function () {
        modal_this = this;
        $(document).on('focusin.modal', function (e) {
            if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
                && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select')
                && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
                modal_this.$element.focus()
            }
        })
    };
    $.ajaxSetup({
        cache: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                toast.error(XMLHttpRequest.responseJSON.returnMsg);
            } else if(XMLHttpRequest.status==500) {
                toast.error("信息输入不完整请仔细核对输入信息");
            } else {
                toast.error("state：" + XMLHttpRequest.status + ", error：" + XMLHttpRequest.statusText);
            }
            Metronic.unblockUI(customGlobal.blockUITarget);
        }
    });
    $.validator.setDefaults({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block help-block-error', // default input error message class
        focusInvalid: true,
        ignore: "",  // validate all fields including form hidden input
        highlight: function (element) { // hightlight error inputs
            $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
        },
        unhighlight: function (element) { // revert the change done by hightlight
            $(element).closest('.form-group').removeClass('has-error'); // set error class to the control group
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error'); // set success class to the control group
        },
        invalidHandler: function (event, validator) { //display error alert on form submit
            toastr.error(i18n["tableWrong"]);
        }
    });
    $.validator.messages.equalTo = i18n["diffInput"];
    $("#menu_" + $("#menuParentId").val()).addClass("active").find("span.arrow").addClass("open");
    $("#menu_" + $("#menuId").val()).addClass("active");
    var $menuSearch = $("#menuSearch").on("keydown", function (e) {
        var $this = $(this);
        var menuId = $this.getGAutoHiddenValue();
        if (e.which == 13 && menuId != undefined && menuId != "") {
            e.preventDefault();
            customGlobal.menuSearch(menuId);
        }
    });
    $("#menuSearchBtn").on("click", function () {
        var menuId = $menuSearch.getGAutoHiddenValue();
        if (menuId != undefined && menuId != "") {
            customGlobal.menuSearch(menuId)
        }
    });
    customGlobal.initUpdatePasswordEvent();
});
var customGlobal = {
    onSortColumnDefault: function (sortColumn, sortDirection) {
        return {
            sortColumn: sortColumn,
            sortDirection: sortDirection
        }
    },
    blockUI: function (target) {
        if (target !== undefined) {
            customGlobal.blockUITarget = target;
            Metronic.blockUI({
                target: target,
                boxed: true,
                message: i18n["loading"]
            });
        } else {
            Metronic.blockUI({
                boxed: true,
                message: i18n["loading"]
            });
        }
    },
    ajaxCallback: function (data) {
        Metronic.unblockUI(customGlobal.blockUITarget);
        if (data.ok) {
            toast.success(data.returnMsg);
            return true;
        } else if (data.error) {
            toast.error(data.returnMsg);
            return false;
        } else if (data.warn) {
            toast.warn(data.returnMsg);
            return true;
        }
    },
    clearFormAndShowDialog: function (dialogId) {
        $("#" + dialogId).find("input:text,input:password,select,textarea").val("").end().modal("show").find("div.form-group").removeClass("has-error");
        $("#" + dialogId).find("input:checkbox").prop("checked",false);
    },
    menuSearch: function (menuId) {
        $.post("develop/menu/menuSearch", {menuId: menuId}, function (data) {
            if (customGlobal.ajaxCallback(data)) {
                location.href = data.returnData.url;
            }
        })
    },
    initUpdatePasswordEvent: function () {
        $("#updatePass").on("click", function () {
            customGlobal.clearFormAndShowDialog("updatePasswordModal");
            $("#updatePasswordDialog").validate({
                rules: {
                    oldPassword: {
                        required: true
                    },
                    reNewPassword: {
                        equalTo: "#newPassword"
                    }
                }
            }).resetForm();
            $("#passwordHelpBlock").html("");
        });

        $("#updatePassword").on("click", function () {
            customGlobal.blockUI("#updatePasswordContent");
            $.ajax({
                url: "security/user/updatePassword",
                data: {
                    oldPassword: $("#oldPassword").val().md5(),
                    newPassword: $("#newPassword").val().md5()
                },
                type: "post",
                success: function (data) {
                    if (customGlobal.ajaxCallback(data)) {
                        $("#updatePasswordModal").modal("hide");
                    }
                }
            });
        });
    },
    generalClass: {
        0: "label-danger",
        1: "label-success"
    }
};

function nextPage(url, stepId) {
    var inputs = $("input");
    //for (var i in inputs) {
    //    if (inputs[i].id != undefined && 'E' == inputs[i].id.charAt(0) && (inputs[i].value == "" || undefined == inputs[i].value)) {
    //        toast.error("请填完信息进入下一页！");
    //        return;
    //    }
    //}
    $.ajax({
        url: basePath + "power/finishStep",
        dataType: "json",
        type: "post",
        //放了三个值，一个填到默认Ex当中，其他两个分别对应属性值和属性名
        data: {
            stepId: stepId
        },
        success: function () {
            if (url != undefined || url != null)
                window.location.href = basePath + url;
        }
    });
}

function formSub() {
    var $form = $("form");
    if ($form.size() == 0) {
        $("body").wrap('<form method="post"></form>');
        $form = $("form");
    }
    switch (arguments.length) {
        case 0:
            $form.attr("method", "post").submit();
            break;
        case 1:
            $form.attr("method", "post").attr("action", arguments[0]).submit();
            break;
        case 2:
            arguments[0].attr("method", "post").attr("action", arguments[1]).submit();
            break;
    }
}

function getUrlByStep(step) {
    if (step == "13") {
        return  {
            url: basePath + "mill/select?menuId=36",
            message: "请先填写-中速磨煤机 :磨煤机选择 "
        }
    }

    if (step == "12") {
        return  {
            url: basePath + "combustion/chimney?menuId=34",
            message: "请先填写-燃烧计算 :烟囱出口直径计算 "
        }
    }

    if (step == "11") {
        return  {
            url: basePath + "combustion/burn?menuId=30",
            message: "请先填写-燃烧计算 :烟气净化系统计算 "
        }
    }
    if (step == "10") {
        return  {
            url: basePath + "combustion/burn?menuId=30",
            message: "请先填写-燃烧计算 :燃烧计算"
        }
    }

    if (step == "9") {
        return  {
            url: basePath + "runcoalbin/design?menuId=27",
            message: "请先填写-原煤仓 :原煤仓设计"
        }
    }
    if (step == "8") {
        return  {
            url: basePath + "boiler/efficiency?menuId=20",
            message: "请先填写-锅炉计算 :锅炉效率及燃煤量"
        }
    }
    if (step == "7") {
        return  {
            url: basePath + "boiler/gasogene?menuId=18",
            message: "请先填写-锅炉计算 :空气及烟气参数"
        }
    }
    if (step == "6") {
        return  {
            url: basePath + "boiler/efficiency?menuId=20",
            message: "请先填写-锅炉计算 :气水参数"
        }
    }
    if (step == "5") {
        return  {
            url: basePath + "nature?menuId=14",
            message: "请先填写-自然条件 :自然条件"
        }
    }
    if (step == "4") {
        return  {
            url: basePath + "quality/boom?menuId=11",
            message: "请先填写-煤质分析:磨损腐蚀爆炸性"
        }
    }
    if (step == "3") {
        return  {
            url: basePath + "quality/grey?menuId=10",
            message: "请先填写-煤质分析:灰分分析"
        }
    }
    if (step == "2") {
        return  {
            url: basePath + "quality/element?menuId=9",
            message: "请先填写-煤质分析:元素分析"
        }
    }
    if (step == "1") {
        return  {
            url: basePath + "quality/industry?menuId=8",
            message: "请先填写-煤质分析:工业分析"
        }
    }
    if (step == "0") {
        return  {
            url: basePath + "power/power?menuId=12",
            message: "方案为空，请新建方案"
        }
    }

    return  {
        url: basePath + "power/power?menuId=12",
        message: "方案为空，请新建方案"
    }
}

var getValueToZero = function (id) {
    var value = $("#" + id).val()
    if (value == "") {
        return 0;
    }
    return value;
}
